<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick, computed, watch } from 'vue'
import { useSettingsStore } from '../stores/settings'
import MarkdownEditor from '../components/MarkdownEditor.vue'
import DirectoryTree from '../components/DirectoryTree.vue'
import TabsPanel from '../components/TabsPanel.vue'
import { Plus, Search, Document } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { INotebook, INote } from '../types/electron'
import '../types' // 导入全局类型声明

// 设置存储
const settingsStore = useSettingsStore()

// 数据
const currentNotebook = ref<INotebook | null>(null)
const currentNote = ref<INote | null>(null)
const searchText = ref('')
const expandedNotebooks = ref<Set<string>>(new Set())
const treeRef = ref<InstanceType<typeof DirectoryTree> | null>(null)
const showSearch = ref(false)
const leftPanelWidth = ref(Number(localStorage.getItem('leftPanelWidth')) || 280)

// 打开的标签页管理
const openedNotes = ref<INote[]>([])
const MAX_TABS = 10

// 设置主题色
const setThemeColor = (color: string) => {
  document.documentElement.style.setProperty('--primary-color', color);
  
  // 根据主色计算相关的衍生色
  const lightColor = color + '20'; // 添加20%透明度作为浅色
  document.documentElement.style.setProperty('--primary-color-light', lightColor);
  document.documentElement.style.setProperty('--primary-color-dark', color);
  
  // 保存到设置中
  settingsStore.setThemeColor(color);
};

// 键盘快捷键处理
const setupKeyboardShortcuts = () => {
  // 监听键盘事件
  window.addEventListener('keydown', (event) => {
    // 不处理文本输入时的快捷键
    if (event.target instanceof HTMLInputElement || 
        event.target instanceof HTMLTextAreaElement) {
      return;
    }
    
    // 新建笔记 - Ctrl+N
    if ((event.ctrlKey || event.metaKey) && event.key === 'n') {
      event.preventDefault();
      if (currentNotebook.value && treeRef.value) {
        treeRef.value.createNote(currentNotebook.value.id);
      }
      return;
    }
    
    // 新建笔记本 - Ctrl+Shift+N
    if ((event.ctrlKey || event.metaKey) && event.shiftKey && event.key === 'N') {
      event.preventDefault();
      if (currentNotebook.value && treeRef.value) {
        if (treeRef.value.canCreateChildNotebook(currentNotebook.value)) {
          treeRef.value.createNotebook(currentNotebook.value.id);
        }
      } else if (treeRef.value) {
        treeRef.value.createNotebook();
      }
      return;
    }
    
    // 重命名 - F2
    if (event.key === 'F2') {
      event.preventDefault();
      if (currentNote.value && treeRef.value) {
        treeRef.value.editNoteTitle(currentNote.value);
      } else if (currentNotebook.value && treeRef.value) {
        treeRef.value.editNotebook(currentNotebook.value);
      }
      return;
    }
    
    // 删除 - Delete
    if (event.key === 'Delete') {
      event.preventDefault();
      if (currentNote.value && treeRef.value) {
        treeRef.value.deleteNote(currentNote.value);
      } else if (currentNotebook.value && treeRef.value) {
        treeRef.value.deleteNotebook(currentNotebook.value);
      }
      return;
    }
    
    // 关闭当前标签页 - Ctrl+W
    if ((event.ctrlKey || event.metaKey) && event.key === 'w') {
      event.preventDefault();
      if (currentNote.value) {
        closeNote(currentNote.value);
      }
      return;
    }
  });
};

// 初始化
onMounted(() => {
  // 添加顶部菜单操作的事件监听
  window.addEventListener('create-notebook', createRootNotebook);
  window.addEventListener('create-note', createCurrentNote);
  window.addEventListener('toggle-search', toggleSearch);
  window.addEventListener('import-data', handleImportData);
  window.addEventListener('export-data', handleExportData);
  window.addEventListener('print-note', handlePrintNote);
  
  // 初始化设置
  settingsStore.initSettings()
  
  // 设置主题色
  const savedColor = settingsStore.getThemeColor()
  if (savedColor) {
    setThemeColor(savedColor)
  }
  
  // 设置键盘快捷键
  setupKeyboardShortcuts();

  // 从本地存储中加载打开的标签
  loadOpenedNotes();
})

// 在onUnmounted钩子中移除事件监听
onUnmounted(() => {
  window.removeEventListener('create-notebook', createRootNotebook);
  window.removeEventListener('create-note', createCurrentNote);
  window.removeEventListener('toggle-search', toggleSearch);
  window.removeEventListener('import-data', handleImportData);
  window.removeEventListener('export-data', handleExportData);
  window.removeEventListener('print-note', handlePrintNote);
  
  // 保存打开的标签到本地存储
  saveOpenedNotes();
});

// 保存打开的标签页到本地存储
const saveOpenedNotes = () => {
  // 只保存id和标题等基本信息
  const notesToSave = openedNotes.value.map(note => ({
    id: note.id,
    title: note.title,
    notebook_id: note.notebook_id
  }));
  localStorage.setItem('openedNotes', JSON.stringify(notesToSave));
};

// 从本地存储加载打开的标签页
const loadOpenedNotes = async () => {
  try {
    const savedNotes = localStorage.getItem('openedNotes');
    if (savedNotes) {
      const parsedNotes = JSON.parse(savedNotes);
      // 加载完整的笔记数据
      for (const noteInfo of parsedNotes) {
        try {
          const fullNote = await window.elec.note.get(noteInfo.id);
          if (fullNote) {
            openedNotes.value.push(fullNote);
          }
        } catch (error) {
          console.error(`加载笔记详情失败: ${noteInfo.id}`, error);
        }
      }
      
      // 如果有打开的笔记，选择第一个
      if (openedNotes.value.length > 0 && !currentNote.value) {
        selectNote(openedNotes.value[0]);
      }
    }
  } catch (error) {
    console.error('加载已打开笔记失败', error);
  }
};

// 切换搜索框
const toggleSearch = () => {
  showSearch.value = !showSearch.value;
  if (showSearch.value) {
    // 当搜索框显示时，自动聚焦
    nextTick(() => {
      const searchInput = document.querySelector('.search-input input');
      if (searchInput) {
        (searchInput as HTMLInputElement).focus();
      }
    });
  } else {
    // 当搜索框隐藏时，清空搜索内容
    searchText.value = '';
  }
};

// 创建根笔记本
const createRootNotebook = () => {
  treeRef.value?.createNotebook(null);
};

// 创建当前笔记本的笔记
const createCurrentNote = () => {
  if (currentNotebook.value) {
    treeRef.value?.createNote(currentNotebook.value.id);
  } else {
    ElMessage.warning('请先选择一个笔记本');
  }
};

// 导入数据
const handleImportData = async () => {
  try {
    await window.elec.importData();
    ElMessage.success('导入成功');
    // 重新加载笔记本和笔记
    await treeRef.value?.loadNotebooks();
  } catch (error) {
    console.error('导入失败', error);
    ElMessage.error('导入失败');
  }
};

// 导出数据
const handleExportData = async () => {
  try {
    await window.elec.exportData();
    ElMessage.success('导出成功');
  } catch (error) {
    console.error('导出失败', error);
    ElMessage.error('导出失败');
  }
};

// 打印当前笔记
const handlePrintNote = async () => {
  if (currentNote.value) {
    try {
      await window.elec.printNote({
        title: currentNote.value.title,
        content: currentNote.value.content
      });
      ElMessage.success('已发送到打印队列');
    } catch (error) {
      console.error('打印失败', error);
      ElMessage.error('打印失败');
    }
  } else {
    ElMessage.warning('请先选择一个笔记');
  }
};

// 选择笔记本
const selectNotebook = (notebook: INotebook) => {
  // 设置当前笔记本
  currentNotebook.value = notebook;
  
  // 如果当前有选中的笔记，但它不属于这个笔记本，就清除当前笔记
  if (currentNote.value && currentNote.value.notebook_id !== notebook.id) {
    currentNote.value = null;
  }
};

// 处理展开状态更新
const handleToggleExpand = (newExpandedNotebooks: Set<string>) => {
  expandedNotebooks.value = new Set(newExpandedNotebooks);
};

// 选择笔记
const selectNote = async (note: INote) => {
  try {
    // 获取完整的笔记信息
    const fullNote = await window.elec.note.get(note.id);
    currentNote.value = fullNote;
    
    // 同时设置当前笔记本
    if (currentNotebook.value?.id !== note.notebook_id && treeRef.value) {
      const notebook = treeRef.value.notebooks.find(n => n.id === note.notebook_id);
      if (notebook) {
        currentNotebook.value = notebook;
      }
    }
    
    // 将笔记添加到标签页
    addNoteToTabs(fullNote);
  } catch (error) {
    console.error('加载笔记详情失败', error);
    ElMessage.error('加载笔记详情失败');
  }
};

// 将笔记添加到标签页
const addNoteToTabs = (note: INote) => {
  // 检查是否已经在标签页中
  const existingIndex = openedNotes.value.findIndex(n => n.id === note.id);
  
  if (existingIndex >= 0) {
    // 如果已存在，更新内容
    openedNotes.value[existingIndex] = { ...note };
  } else {
    // 如果不存在，检查是否超出最大标签数
    if (openedNotes.value.length >= MAX_TABS) {
      // 移除最早打开的标签
      openedNotes.value.shift();
    }
    
    // 添加到标签页
    openedNotes.value.push({ ...note });
  }
  
  // 保存到本地存储
  saveOpenedNotes();
};

// 关闭笔记标签页
const closeNote = (note: INote) => {
  const index = openedNotes.value.findIndex(n => n.id === note.id);
  
  if (index >= 0) {
    openedNotes.value.splice(index, 1);
    
    // 如果关闭的是当前笔记，需要切换到另一个笔记
    if (currentNote.value && currentNote.value.id === note.id) {
      if (openedNotes.value.length > 0) {
        // 选择下一个或前一个笔记
        const nextIndex = index < openedNotes.value.length ? index : index - 1;
        selectNote(openedNotes.value[nextIndex]);
      } else {
        currentNote.value = null;
      }
    }
    
    // 保存到本地存储
    saveOpenedNotes();
  }
};

// 关闭所有标签页，可选择保留指定的标签
const closeAllNotes = (exceptId?: string) => {
  if (exceptId) {
    // 保留指定的标签
    const keepNote = openedNotes.value.find(n => n.id === exceptId);
    openedNotes.value = keepNote ? [keepNote] : [];
    
    // 确保当前笔记是保留的笔记
    if (keepNote) {
      currentNote.value = keepNote;
    } else {
      currentNote.value = null;
    }
  } else {
    // 关闭所有标签
    openedNotes.value = [];
    currentNote.value = null;
  }
  
  // 保存到本地存储
  saveOpenedNotes();
};

// 关闭除指定标签外的所有标签
const closeOtherNotes = (id: string) => {
  const keepNote = openedNotes.value.find(n => n.id === id);
  
  if (keepNote) {
    openedNotes.value = [keepNote];
    currentNote.value = keepNote;
  }
  
  // 保存到本地存储
  saveOpenedNotes();
};

// 处理笔记本创建
const handleNotebookCreated = (notebook: INotebook) => {
  // 选择新创建的笔记本
  selectNotebook(notebook);
};

// 处理笔记本删除
const handleNotebookDeleted = (notebook: INotebook) => {
  // 如果当前选中的就是被删除的笔记本，清空选择
  if (currentNotebook.value?.id === notebook.id) {
    currentNotebook.value = null;
    currentNote.value = null;
  }
  
  // 关闭属于被删除笔记本的所有标签页
  openedNotes.value = openedNotes.value.filter(note => note.notebook_id !== notebook.id);
  saveOpenedNotes();
};

// 处理笔记创建
const handleNoteCreated = (note: INote) => {
  // 选择新创建的笔记
  selectNote(note);
};

// 处理笔记删除
const handleNoteDeleted = (note: INote) => {
  // 关闭被删除的笔记的标签页
  closeNote(note);
};

// 保存笔记
const saveNote = async (content: string) => {
  if (!currentNote.value) return;
  
  try {
    const updatedNote = await window.elec.note.update(currentNote.value.id, {
      content
    });
    
    // 更新当前笔记和打开的标签页中的笔记内容
    if (currentNote.value) {
      currentNote.value.content = content;
      
      // 更新标签页中的笔记
      const index = openedNotes.value.findIndex(n => n.id === currentNote.value?.id);
      if (index >= 0) {
        openedNotes.value[index].content = content;
      }
    }
    
    if (!settingsStore.autoSave) {
      ElMessage.success('笔记保存成功');
    }
  } catch (error) {
    console.error('保存笔记失败', error);
    ElMessage.error('保存笔记失败');
  }
};

// 更新笔记内容
const updateNoteContent = (content: string) => {
  if (currentNote.value) {
    currentNote.value.content = content;
    
    // 如果启用了自动保存，则在内容变化时自动保存
    if (settingsStore.autoSave) {
      saveNote(content);
    }
  }
};

// 更新笔记标题
const updateNoteTitle = async (title: string) => {
  if (!currentNote.value || currentNote.value.title === title) return;
  
  try {
    await window.elec.note.update(currentNote.value.id, { title });
    
    // 更新当前笔记的标题
    currentNote.value.title = title;
    
    // 更新标签页中笔记的标题
    const index = openedNotes.value.findIndex(n => n.id === currentNote.value?.id);
    if (index >= 0) {
      openedNotes.value[index].title = title;
    }
    
    // 通知目录树更新
    await treeRef.value?.loadNotes(currentNote.value.notebook_id);
    
    ElMessage.success('笔记标题更新成功');
  } catch (error) {
    console.error('更新笔记标题失败', error);
    ElMessage.error('更新笔记标题失败');
  }
};

// 保存宽度到本地存储
const savePanelWidth = () => {
  localStorage.setItem('leftPanelWidth', leftPanelWidth.value.toString())
}

// 拖拽分隔条
const startResize = (event: MouseEvent) => {
  const startX = event.clientX;
  const startWidth = leftPanelWidth.value;

  const handleResize = (event: MouseEvent) => {
    const deltaX = event.clientX - startX;
    leftPanelWidth.value = Math.max(200, Math.min(500, startWidth + deltaX));
  };

  const stopResize = () => {
    document.removeEventListener('mousemove', handleResize);
    document.removeEventListener('mouseup', stopResize);
    savePanelWidth();
  };

  document.addEventListener('mousemove', handleResize);
  document.addEventListener('mouseup', stopResize);
};
</script>

<template>
  <div class="home-container">
    <!-- 左侧内容 -->
    <div class="left-panel" :style="{ width: `${leftPanelWidth}px` }">
      <!-- 搜索栏 -->
      <div v-if="showSearch" class="search-container">
        <el-input
          v-model="searchText"
          placeholder="搜索笔记..."
          prefix-icon="el-icon-search"
          clearable
          class="search-input"
        />
      </div>
      
      <!-- 目录树 -->
      <DirectoryTree 
        ref="treeRef"
        :current-notebook="currentNotebook"
        :current-note="currentNote"
        :search-text="searchText"
        :initial-expanded-ids="Array.from(expandedNotebooks)"
        @select-notebook="selectNotebook"
        @select-note="selectNote"
        @toggle-expand="handleToggleExpand"
        @notebook-created="handleNotebookCreated"
        @notebook-deleted="handleNotebookDeleted"
        @note-created="handleNoteCreated"
        @note-deleted="handleNoteDeleted"
      />
    </div>
    
    <!-- 拖拽分隔条 -->
    <div 
      class="resize-handle" 
      @mousedown="startResize"
    ></div>
    
    <!-- 右侧编辑器 -->
    <div class="right-panel">
      <!-- 标签页 -->
      <TabsPanel
        :notes="openedNotes"
        :active-note-id="currentNote?.id || null"
        @select="selectNote"
        @close="closeNote"
        @close-all="closeAllNotes"
        @close-others="closeOtherNotes"
      />
      
      <div v-if="!currentNote" class="empty-state">
        <div class="empty-message">
          <el-icon><Document /></el-icon>
          <p>请选择或创建一个笔记</p>
        </div>
      </div>
      
      <MarkdownEditor 
        v-else
        v-model="currentNote.content" 
        :title="currentNote.title"
        @update:modelValue="updateNoteContent"
        @update:title="updateNoteTitle"
        @save="saveNote"
      />
    </div>
  </div>
</template>

<style scoped>
.home-container {
  display: flex;
  height: 100%;
  width: 100%;
  overflow: hidden;
}

.left-panel {
  width: 280px;
  height: 100%;
  border-right: 1px solid var(--border-color);
  display: flex;
  flex-direction: column;
  background-color: var(--sidebar-bg-color, #f8f8f8);
}

.search-container {
  padding: 10px;
  border-bottom: 1px solid var(--border-color);
}

.search-input {
  width: 100%;
}

.right-panel {
  flex: 1;
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: var(--text-muted-color);
}

.empty-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.empty-message .el-icon {
  font-size: 48px;
  opacity: 0.5;
}

.empty-message p {
  font-size: 16px;
  margin: 0;
}

.resize-handle {
  width: 1px;
  height: 100%;
  cursor: col-resize;
  background-color: var(--border-color);
  transition: background-color 0.2s;
  position: relative;
  z-index: 1;
}

.resize-handle::after {
  content: '';
  position: absolute;
  top: 0;
  left: -2px;
  width: 5px;
  height: 100%;
  cursor: col-resize;
  background-color: transparent;
}

.resize-handle:hover,
.resize-handle:active {
  background-color: var(--primary-color);
}
</style>
